package com.momomian.common.mail;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Objects;

/**
 * @author momomian
 * @version 1.0
 * @date 2020/7/2
 * @description 邮箱发送
 **/
@Slf4j
@Component
public class SendMailUtil {

    /**
     * 多个接收人，分隔符
     */
    private static final String DELIMITER = ";";

    @Autowired
    private JavaMailSenderImpl createMailSender;



    /**
     * 发送邮件
     *
     * @param fromName 发送人名
     * @param to       接受人邮箱
     * @param subject  主题
     */

    public void sendHtmlMail(String fromName, String to, String subject, String html) throws Exception {
        if (StringUtils.isEmpty(to)) {
            log.info("邮箱接收地址为空");
            return;
        }
        sendAggr(fromName, to, subject, html, createMailSender);
    }

    public void sendAggr(String fromName, String to, String subject, String html, JavaMailSenderImpl sender) {
        try {
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            if (to.contains(DELIMITER)) {
                String[] toBy = to.split(DELIMITER);
                InternetAddress[] internetAddress = new InternetAddress[toBy.length];
                for (int i = 0; i < toBy.length; i++) {
                    internetAddress[i] = new InternetAddress(toBy[i]);
                }
                mimeMessage.setRecipients(Message.RecipientType.TO, internetAddress);
            } else {
                messageHelper.setTo(to);
            }

            // 设置utf-8或GBK编码，否则邮件会有乱码
            messageHelper.setFrom(Objects.requireNonNull(createMailSender.getUsername()), fromName);
            messageHelper.setSubject(subject);
            messageHelper.setText(html, true);
            createMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("mail has error ", e);
        }
    }
}
